package top.whysu.gps.service.system.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.whysu.gps.dao.system.CategoryDao;
import top.whysu.gps.dto.system.CategoryTreeDTO;
import top.whysu.gps.service.system.AccountService;
import top.whysu.gps.service.system.CategoryService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 导航菜单业务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CategoryServiceImpl.class);
    private BigDecimal rootId = BigDecimal.ZERO;

    @Resource
    private CategoryDao categoryDao;
    @Resource
    private AccountService accountService;

    @Override
    public List<CategoryTreeDTO> selectMenuTree() {
        // 当前账户
        BigDecimal accountId = accountService.selectCurrentAccount().getId();
        // 查询当前用户的所有菜单
        Map<String, Object> params = new HashMap<>(1);
        params.put("accountId", accountId);
        List<CategoryTreeDTO> childNodes = categoryDao.selectMenuTree(params);
        return treeMenuList(childNodes, BigDecimal.valueOf(0));
    }

    /**
     * 菜单树递归
     */
    private List<CategoryTreeDTO> treeMenuList(List<CategoryTreeDTO> childNodes, BigDecimal parentId) {
        List<CategoryTreeDTO> childMenu = new ArrayList<>();
        for (CategoryTreeDTO menu : childNodes) {
            BigDecimal menuId = menu.getId();
            BigDecimal pid = menu.getParentId();
            if (parentId.equals(pid)) {
                List<CategoryTreeDTO> cNode = treeMenuList(childNodes, menuId);
                menu.setChildren(cNode);
                childMenu.add(menu);
            }
        }
        return childMenu;
    }

}
